
import { defineAsyncComponent, toRaw, nextTick, resolveComponent } from 'vue';
import DebugView from '../DebugView/DebugView.mjs';

let LogView = defineAsyncComponent(() => {
    return new Promise((resolve) => {
        fetch('./components/LogView/LogView.html').then((res) => res.text()).then(async (template) => {
            let link = document.createElement('link');
            link.rel = 'stylesheet';
            link.href = './components/LogView/LogView.css';
            document.head.appendChild(link);

            resolve({
                name: 'LogView',
                props: ['levelChangeCallback', 'isDebug', 'style', 'sendMessage', 'scene'],
                components: { DebugView },
                template,
                data() {
                    return {
                        split1: 0.5,
                        enabled: true,
                        followNewLog: true,
                        maxLogCount: 500,
                        logList: [],
                        filterText: '',
                        filterExcludeText: 'animationframe;',
                        logBuffer: [],
                        logType: ['sys', 'usr'],
                        logLevel: [3, 4, 5],
                        usrLogLevel: 5,
                        sysLogLevel: 5,
                        lastMsg: null,
                        logDivColumns: [
                            {
                                title: OB_IDE.$t('消息'),
                                key: 'msg',
                                className: 'logTableColumnNormal',
                                render: (h, params) => {
                                    return h('div', { class: ['level' + params.row.level] }, [
                                        h(resolveComponent('tooltip'), {
                                            content: params.row.msg,
                                            transfer: true
                                        }, params.row.msg)
                                    ]);
                                }
                            },
                            {
                                title: OB_IDE.$t('来源'),
                                key: 'stackpath',
                                className: 'logTableColumnNormal',
                                render: (h, params) => {
                                    return h('div', [
                                        h('a', {
                                            on: {
                                                click: this.clickTableCell(params.row)
                                            },
                                        }, params.row.stackpath)
                                    ]);
                                }
                            },
                            {
                                title: OB_IDE.$t('类型'),
                                key: 'type',
                                className: 'logTableColumnType logTableColumnNormal',
                                width: '35px',
                                filters: [
                                    {
                                        label: OB_IDE.$t('系统'),
                                        value: 1
                                    },
                                    {
                                        label: OB_IDE.$t('用户'),
                                        value: 2
                                    }
                                ],
                                filterMultiple: false,
                                filterMethod(value, row) {
                                    if (value === 1) {
                                        return row.type === 'sys';
                                    } else if (value === 2) {
                                        return row.type === 'usr';
                                    }
                                }
                            },
                            {
                                title: OB_IDE.$t('等级'),
                                key: 'level',
                                className: 'logTableColumnLevel logTableColumnNormal',
                                width: '35px',
                                filters: [
                                    {
                                        label: 0,
                                        value: 0
                                    },
                                    {
                                        label: 1,
                                        value: 1
                                    },
                                    {
                                        label: 2,
                                        value: 2
                                    },
                                    {
                                        label: 3,
                                        value: 3
                                    },
                                    {
                                        label: 4,
                                        value: 4
                                    },
                                    {
                                        label: 5,
                                        value: 5
                                    },
                                    {
                                        label: 6,
                                        value: 6
                                    },
                                    {
                                        label: 7,
                                        value: 7
                                    },
                                    {
                                        label: 8,
                                        value: 8
                                    },
                                    {
                                        label: 9,
                                        value: 9
                                    },
                                    {
                                        label: 10,
                                        value: 10
                                    },
                                ],
                                // filteredValue: [3, 4, 5, 6],
                                filterMultiple: true,
                                filterMethod(value, row) {
                                    return row.level === value;
                                }
                            },
                            {
                                title: OB_IDE.$t('时间'),
                                key: 'time',
                                className: 'logTableColumnTime logTableColumnNormal',
                                width: '60px'
                            },
                        ]
                    }
                },
                watch: {
                    isDebug() {
                        if (this.isDebug) {
                            this.sysLogLevel = 4;
                            this.usrLogLevel = 4;
                        } else {
                            this.sysLogLevel = 5;
                            this.usrLogLevel = 5;
                        }
                        this.logLevelChange();
                    }
                },
                computed: {
                    filteredLogList() {
                        if (this.filterText.length === 0 && this.filterExcludeText.length === 0) {
                            return this.logList;
                        } else {
                            let filterTexts = this.filterText.toLowerCase().split(';').filter(m => m.length > 0);
                            let filterExcludeTexts = this.filterExcludeText.toLowerCase().split(';').filter(m => m.length > 0);
                            function has(str, arr) {
                                for (let i = 0; i < arr.length; i++) {
                                    if (str.indexOf(arr[i]) >= 0) return true;
                                }
                                return false;
                            }

                            return this.logList.filter((item) => {
                                let level = item.level;
                                let type = item.type;
                                if (type === 'usr' && level < this.usrLogLevel) return false;
                                if (type === 'sys' && level < this.sysLogLevel) return false;

                                let msg = item.msg.toLowerCase();
                                if (has(msg, filterExcludeTexts)) {
                                    return false;
                                }
                                if (has(msg, filterTexts)) {
                                    return true;
                                }
                                if(!item.stackpath){
                                    item.stackpath = '';
                                }
                                let stackpath = item.stackpath.toLowerCase();
                                if (has(stackpath, filterExcludeTexts)) {
                                    return false;
                                }
                                if (has(stackpath, filterTexts)) {
                                    return true;
                                }
                                return filterTexts.length == 0;
                            })
                        }
                    }
                },
                methods: {
                    debug(name, args, level, stack, block) {
                        let debugview = this.$refs.debugview;
                        debugview.debug(name, args, level, stack, block);
                    },
                    clickTableCell(d) {
                        let that = this;
                        return () => {
                            that.tableCell(d);
                        }
                    },
                    tableCell(data) {
                        this.$root.gotoSrc(data.block);
                        // if (data.cmd === 'text') {
                        //     this.$root.gotoSrc(data.block);
                        //     return;
                        // }
                        // switch (data.msg) {
                        //     default:
                        //         this.$root.gotoSrc(data.block);
                        // }
                    },
                    clearLog() {
                        this.logList = [];
                        this.logBuffer = [];
                    },
                    logLevelChange() {
                        let arg = { usrLogLevel: this.usrLogLevel, sysLogLevel: this.sysLogLevel };
                        this.levelChangeCallback(arg);
                    },
                    toggleFollowNewLog() {
                        this.followNewLog = !this.followNewLog;
                    },
                    putLog(v) {
                        let level = v.level;
                        let type = v.type;
                        if (type === 'usr' && level < this.usrLogLevel) return false;
                        if (type === 'sys' && level < this.sysLogLevel) return false;
                        function checkTime(i) {
                            if (i < 10) {
                                i = "0" + i;
                            }
                            return i;
                        }
                        var today = new Date();//定义日期对象   
                        var hh = today.getHours();//通过日期对象的getHours方法返回小时   
                        var mm = today.getMinutes();//通过日期对象的getMinutes方法返回分钟   
                        var ss = today.getSeconds();//通过日期对象的getSeconds方法返回秒  
                        mm = checkTime(mm);
                        ss = checkTime(ss);
                        let time = hh + ':' + mm + ':' + ss;
                        v.time = time;
                        this.logBuffer.push(v);
                        if (this.logBuffer.length > this.maxLogCount) {
                            this.logBuffer = this.logBuffer.slice(-this.maxLogCount);
                        }
                        if (v.level >= 5) {
                            if (!v.stype) {
                                if (v.level >= 8) {
                                    v.stype = 'error';
                                } else if (v.level == 7) {
                                    v.stype = 'warning';
                                } else if (v.level == 6) {
                                    v.stype = 'success';
                                } else {
                                    v.stype = 'processing';
                                }
                            }
                            if (!v.content) {
                                v.content = v.msg;
                            }
                            this.lastMsg = v;
                        }
                    },
                    log(evt) {
                        let v = evt.data.arg;
                        this.putLog(v);
                    },
                    updateLogUI() {
                        if (this.logBuffer.length == 0) {
                            return;
                        }
                        this.logList.push(...this.logBuffer);
                        if (this.logList.length > this.maxLogCount) {
                            this.logList = this.logList.slice(-this.maxLogCount);
                        }
                        this.logBuffer = [];
                        if (this.followNewLog) {
                            setTimeout(() => {
                                let div = this.$refs.logDiv;
                                div.scrollTop = Number.MAX_SAFE_INTEGER;
                            }, 1);
                        }
                    },
                },
                mounted() {
                    let that = this;
                    function requestAniF() {
                        window.requestAnimationFrame(() => {
                            if (!that.enabled) {
                                return;
                            }
                            that.updateLogUI();
                            requestAniF();
                        });
                    }
                    requestAniF();
                },
                beforeUnmount() {
                    this.enabled = false;
                },
            });
        });
    });
});
export default LogView;